package com.serookie.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.serookie.entity.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author kevintam
 * @version 1.0
 * @date 2021/3/21 23:28
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler{
    //当登录后,访问接口没有权限的时候,该处理类的方法被调用
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        Result error = Result.error().message("权限不够,请联系管理员");
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(error));
        writer.flush();
        writer.close();
    }
}
